import * as name from '../config/constant'
import { getCookie,setCookie } from '../config/lib'
import { disk_init } from './disk'
import fetch from 'isomorphic-fetch'

export const init = (dispatch) => {
  let token = getCookie('token')
  if(!token){
    return dispatch(initFail())
  }else {
    return (dispatch) => {fetch(name._API+'/init?token='+token,{
      method: 'GET',
      mode: 'cors',
      headers: {
        'Accept': 'application/json',
      }
    })
    .then(response => response.json())
    .then(function success(response){
      if(response.code===200){
        dispatch(initSuccess(response,token))
        dispatch(disk_init(dispatch,token))
      }
      if(response.code===401) dispatch(initFail())
    })
  }
}
}

export const validateToken = (dispatch,token) => {
  return (dispatch) => {fetch(name._API+'/init?token='+token,{
    method: 'GET',
    mode: 'cors',
    headers: {
      'Accept': 'application/json',
    }
  })
  .then(response => response.json())
  .then(function success(response){
    if(response.code===401)return dispatch(initFail())
  })
}
}

export const initSuccess = (response,token) => {
  return {
    type: name.INIT_SUCCESS,
    token: token,
    uid: response.uid,
    username: response.username,
    login: true
  }
}

export const initFail = () => {
  return{
    type: name.INIT_FAIL,
    login:false,
    msg:'未登录！'
  }
}

export const Login = (username,password) => {
  let request = {
    "username":username,
    "password":password
  }
  return (dispatch) => {fetch(name._API+'/login',{
    method: 'POST',
    mode: 'cors',
    body:JSON.stringify(request)
  })
  .then(response => response.json())
  .then(function success(response){
    if(response.code===200){
      dispatch(LoginSuccess(dispatch,response))
    }
    else if (response.code===401) dispatch(LoginFail(response))
  })
  }
}

export const LoginSuccess = (dispatch,response) => {
  setCookie('token',response.token,7)
  dispatch(disk_init(dispatch,response.token))
  return {
    type: name.LOGIN_SUCCESS,
    msg: '登录成功',
    token: response.token,
    uid: response.uid,
    username: response.username,
    login: true
  }
}

export const LoginFail = (response) => {
  return {
    type: name.LOGIN_FAIL,
    error: response.error,
    login: false
  }
}

export const Logout = () => {
  setCookie('token',null,0)
  return {
    type: name.LOGOUT,
    token: ' ',
    msg: '下车',
    login:false
  }
}
